package com.mc.mq.rocketmq.order;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class Producer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer=new DefaultMQProducer("group1");
        //2.指定Nameserver地址
        producer.setNamesrvAddr("192.168.3.31:9876;192.168.3.32:9876;");
        //3.启动producer
        producer.start();
        //构建消息集合
        List<OrderStep> orderSteps=OrderStep.buildOrders();
        //发消息
        for (int i = 0; i < orderSteps.size(); i++) {
            String body=orderSteps.get(i)+"";
            Message message=new Message("OrderTopic","Order","i"+i,body.getBytes(StandardCharsets.UTF_8));
            SendResult sendResult=producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    long orderId=(long)arg;
                    long index = orderId% mqs.size();
                    return mqs.get((int)index);
                }
            },orderSteps.get(i).getOrderId());
            System.out.println("发送结果：" + sendResult);
        }
        producer.shutdown();
    }

}
